
using System.Threading;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Collections.Generic;
namespace com.tc.gateway.tunnel
{

    public class Tunnel
    {
        TcpTunnelServer server;
        Stream outd;
        TcpClient socket;
        Thread ts;
        public Tunnel(Stream outdd, TcpClient socket, TcpTunnelServer s)
        {

            this.outd = outdd;
            this.socket = socket;
            this.server = s;
        }
        public void start()
        {
            ts = new Thread(run);
            ts.Start();
        }
        public void run()
        {
            byte[] buffer = new byte[256];

            try
            {
                while (true)
                {

                    int l = socket.GetStream().Read(buffer, 0, buffer.Length);
                    outd.Write(buffer, 0, l);
                }
            }
            catch (IOException e)
            {

                server.tunnels.Remove(this);
            }
        }

        public void write(byte[] buffer, int offset, int count)
        {
            try
            {
                socket.GetStream().Write(buffer, offset, count);
            }
            catch (IOException e)
            {

                server.tunnels.Remove(this);
            }
        }

        public void interrupt()
        {
            // TODO Auto-generated method stub
            ts.Abort();
            try
            {
                socket.Close();
            }
            catch (IOException e)
            {
                // TODO Auto-generated catch block
                //	e.printStackTrace();
            }
        }


    }
}